package com.tanhua.sso.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.AliyunSMSConfig;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


@Service
public class SmsService {
    public static final String REDIS_KEY_PREFIX = "CHECK_CODE_";
    //注入配置类
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsService.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /*
        发送验证码短信   云之讯
        @return  返回验证码或null
     */
    public String sendSms(String mobile) {

        //设置短信请求的地址
        String url = "https://open.ucpaas.com/ol/sms/sendsms";

        //设置Map集合封装API接口对接参数
        Map<String, Object> params = new HashMap<>();
        params.put("sid", "181fa2a981a8ec66ac2b6a3e4b46c41a");
        params.put("token", "42ef8640ee66e6b468540cb08ac3ae82");
        params.put("appid", "62649294e31143438656f0ab8361a886");
        params.put("templateid", "578582");
        params.put("mobile", mobile);

        //生成6位数验证
        params.put("param", RandomUtils.nextInt(100000, 999999));

        ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, params, String.class);

        //获取返回的信息
        String body = responseEntity.getBody();

        try {
            JsonNode jsonNode = MAPPER.readTree(body);

            //000000表示发送成功
            if (StringUtils.equals(jsonNode.get("code").textValue(), "000000")) {
                return String.valueOf(params.get("param"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;


    }

    /*
        发送验证码到redis
     */
    public Map<String, Object> sendCheckCode(String mobile) {
        Map<String, Object> result = new HashMap<>(2);

        try {
            String redisKey = REDIS_KEY_PREFIX + mobile;
            String value = this.redisTemplate.opsForValue().get(redisKey);
            //判断value是否还存在
            if (StringUtils.isNotEmpty(value)) {
                result.put("code", 1);
                result.put("msg", "上一次发送的验证码还未失效");
                return result;
            }

            //调用云之讯短信接口
            //String code = this.sendSms(mobile);

            //调用阿里云短信接口
            //String code = this.sendSmsAliyun(mobile);

            String code = "123456";
            if (null == code) {
                result.put("code", 2);
                result.put("msg", "发送短信验证码失败");
                return result;
            }

            //发送验证码成功
            result.put("code", 3);
            result.put("msg", "ok");

            //将验证码存储到redis,5分钟后失效
            this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(1));
            return result;
        } catch (Exception e) {
            LOGGER.error("发送验证码出错！" + mobile, e);

            result.put("code", 4);
            result.put("msg", "发送验证码出现异常");
            return result;
        }

    }


    /*
        阿里云短信认证
     */
    public String sendSmsAliyun(String mobile) {

        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId()
                , this.aliyunSMSConfig.getAccessKeyId()
                , this.aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile);   //接受短信号码
        request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName());        //签名名称
        request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode());  //模板Id
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            if (StringUtils.contains(response.getData(), "\"Code\":\"OK\"")) {
                return code;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }
}
